package image_ser

import (
	"fmt"
	"ginBolg/global"
	"ginBolg/models"
	"ginBolg/models/ctype"
	"ginBolg/plugins/qiniu"
	"ginBolg/utils"
	"io/ioutil"
	"mime/multipart"
	"strings"
)

var (
	// WhiteImageList 图片后缀白名单
	WhiteImageList = []string{
		"jpg", "jpeg", "png", "gif", "webp", "ico", "svg", "tiff",
	}
)

type FileUploadResponse struct {
	FileName string `json:"file_name"`
	Success  bool   `json:"success"`
	Msg      string `json:"msg"`
}

// ImageUploadService 文件上传的方法
func (ImageService) ImageUploadService(file *multipart.FileHeader) (res *FileUploadResponse) {
	fileName := file.Filename
	res.FileName = fileName
	res.Success = false
	// 文件白名单判断
	nameList := strings.Split(fileName, ".")
	suffix := strings.ToLower(nameList[len(nameList)-1])
	if !utils.IsInList(suffix, WhiteImageList) {
		res.Msg = "文件格式错误"
		return
	}
	// 判断图片大小
	size := float64(file.Size) / 1024 / 1024
	if size > float64(global.Config.Upload.Size) {
		res.Msg = fmt.Sprintf("图片大小超过 %d MB限制", global.Config.Upload.Size)
		return
	}

	// 读取文件内容
	fileObj, err := file.Open()
	if err != nil {
		global.Log.Error(err)
	}
	byteData, err := ioutil.ReadAll(fileObj)
	imageHash := utils.Md5(byteData)
	// 去数据库中查寻，图片是否存在
	var bannerModel models.BannerModel
	tx := global.DB.Take(&bannerModel, "hash = ?", imageHash)
	if tx.Error == nil {
		// 找到了
		res.Msg = "上传成功"
		return
	}

	if global.Config.QiNiu.Enable {
		filePath, err := qiniu.UploadImage(byteData, fileName, global.Config.QiNiu.Prefix)
		if err != nil {
			res.Msg = err.Error()
			return
		}
		res.FileName = filePath

		// 图片入库
		global.DB.Create(&models.BannerModel{
			Path:      filePath,
			Hash:      imageHash,
			Name:      fileName,
			ImageType: ctype.QiNiu,
		})

		res.Msg = "上传成功"
		res.Success = true
		return
	}
	res.Msg = "七牛云上传未开启"
	return
}
